import {
  hsetStorage,
  hnavigateBack,
  hshowToast
} from '../../static/htools.wx'
import {
  hrequestPost
} from '../../static/hunit.wx'
import api from '../../assets/api'
const {
  authorLogin
} = api
import {
  encrypt
} from '../../static/rsaEncrypt'
import WxValidate from '../../static/WxValidate'
Page({
  data: {
    username: '',
    password: '',
    bottom: 0,
  },
  onLoad() {
    this.initValidate() //验证规则函数
  },
  // 双向绑定用户名
  bindUsername(e) {
    this.setData({
      username: e.detail.value
    });
  },
  // 双向绑定密码
  bindPassword(e) {
    this.setData({
      password: e.detail.value
    });
  },
  showModal(error) {
    wx.showModal({
      content: error.msg,
      showCancel: false,
    })
  },
  initValidate() {
    const rules = {
      username: {
        required: true
      },
      password: {
        required: true
      }
    }
    const messages = {
      username: {
        required: '请输入用户名'
      },
      password: {
        required: '请输入密码'
      }
    }
    this.WxValidate = new WxValidate(rules, messages)
  },
  // 校验与登录
  async formSubmit(e) {
    const params = e.detail.value
    //校验表单
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0]
      this.showModal(error)
      return false
    }
    //登录提交操作
    let _password = encrypt(this.data.password);
    let _jsonData = {
      "password": _password,
      "username": this.data.username
    }
    let _res = await hrequestPost(authorLogin, _jsonData)
    console.log(_res);

    if (_res.statusCode === 200) {
      hshowToast('登录成功');
      hsetStorage('isAuthor', 1);
      hsetStorage('token', _res.data.token);
      hsetStorage('deptId', _res.data.user.user.dept.id);
      hsetStorage('userName', _res.data.user.user.username);
      hsetStorage('userHeadPic', _res.data.user.user.avatarPath);
      hsetStorage('userPhone', _res.data.user.user.phone);
      if (_res.data.deptArea!=null) {
        hsetStorage('deptArea', _res.data.deptArea.replace(/,/g, ''));
      }
      hnavigateBack(1)
    } else {
      hshowToast(_res.data.message);
      return false
    }
  },
  //取消
  handleCancel() {
    hnavigateBack(1)
  },
  //输入聚焦 上推输入框
  foucus(e) {
    this.setData({
      bottom: e.detail.height
    })
  },
  //失去聚焦 输入框回到原来位置
  blur(e) {
    this.setData({
      bottom: 0
    })
  },
})